#include <stdio.h>
#include <string.h>
#include <malloc.h>

#include "phone.h"
#include "fileio.h"
#include "scrio.h"

void save(booktype &book,char *name=NULL) {
  FILE *f;
  int i;
  if (name==NULL) { name=book.fname; }
  else {
    delete book.fname;
    book.fname=new char[strlen(name)+1];
    strcpy(book.fname,name); 
  }
  if ((f=fopen(name,"w+"))==NULL) {
    error("filio.cpp: save: error opening %s",name);
    getkey();
    return;
  } else {
    fprintf(f,"%i\n",book.size);
    for (i=0;i<book.size;i++) {
      fprintf(f,"%s ",book.entries[i].first);
      fprintf(f,"%s ",book.entries[i].last);
      fprintf(f,"%s ",book.entries[i].area);
      fprintf(f,"%s ",book.entries[i].number);
      fprintf(f,"%s\n",book.entries[i].des);
    }
    fclose(f);
  }
}

void open(booktype &book,char *name=NULL) {
  FILE *f;
  int i;
  //  free(book.entries);
  if (name==NULL) { name=book.fname; }
  else { 
    book.fname=new char[strlen(name)+1];
    strcpy(book.fname,name); 
  }
  if ((f=fopen(name,"r"))==NULL) {
    error("filio.cpp: open: error opening %s\n",name);
    getkey();
    book.size=0;
    book.entries=new entrytype[0];
    return;
  } else {
    fscanf(f,"%i",&book.size);
    if ((book.entries=new entrytype[book.size])==NULL) {
      printf("fileio.cpp: open: error allocating memory (%i entries) for book\n",book.size);
      getchar();
      return;
    }
    for (i=0;i<book.size;i++) {
      fscanf(f,"%s",book.entries[i].first);
      fscanf(f,"%s",book.entries[i].last);
      fscanf(f,"%s",book.entries[i].area);
      fscanf(f,"%s",book.entries[i].number);
      strcpy(book.entries[i].des,"");
      fscanf(f,"%[^\n]s",book.entries[i].des);
    }
    fclose(f);
  }
}
